package android.net.bootstrap;

import io.netty.channel.*;
import io.netty.channel.socket.oio.OioClientSocketChannelFactory;

import java.net.SocketAddress;
import java.util.concurrent.Executors;

public class ClientBootstrap {
    private ChannelFactory factory = new OioClientSocketChannelFactory(Executors.newSingleThreadExecutor());
    private ChannelPipeline pipeline;
    private ChannelPipelineFactory pipelineFactory;

    /**
     * Attempts a new connection with the specified {@code remoteAddress}
     * , the local address of a new channel is determined
     * automatically.
     *
     * @return a future object which notifies when this connection attempt
     *         succeeds or fails
     * @throws ChannelPipelineException if this bootstrap's
     *                                  failed to create a new {@link ChannelPipeline}
     */
    public ChannelFuture connect(SocketAddress remoteAddress) {
        if (remoteAddress == null) {
            throw new NullPointerException("remoteAddress");
        }

        ChannelPipeline pipeline;
        try {
            pipeline = pipelineFactory.getPipeline();
        } catch (Exception e) {
            throw new ChannelPipelineException("Failed to initialize a pipeline.", e);
        }

        // Set the options.
        Channel ch = factory.newChannel(pipeline);

        // Connect.
        return ch.connect(remoteAddress);
    }

    public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) {
        this.pipelineFactory = pipelineFactory;
    }
}